<script setup>
import {ref, watch} from "vue";
import {categoriesGetAllAPI, gameCategoryAddAPI} from "@/api/AdminApi/category.js";
import 'element-plus/theme-chalk/el-message.css'
import {ElMessage} from "element-plus";

const categoryInfo = ref({
  gameId: null,
  categories: []
})

// 删除分类
const handleDelete = (id) => {
  categoryInfo.value.categories = categoryInfo.value.categories.filter(category => category.id !== id);
}

// 提交按钮
const submit = async (gameId) => {
  categoryInfo.value.gameId = gameId
  const res = await gameCategoryAddAPI(categoryInfo.value)
  if (res.code === 1) {
    return res.code
  } else {
    ElMessage.error(res.msg)
  }
}

// 校验
const validate = () => {
  if (categoryInfo.value.categories.length === 0) {
    return false
  }
}

// 父组件调用提交方法
defineExpose({
  submit:submit,
  validate:validate
})

const AllCategories= ref([])
const dialogVisible = ref(false)
const categoryName = ref()
// 打开分类列表
const showAllCategories = () => {
  dialogVisible.value = true
}

// 对话框打开时
const handleOpen = async () => {
  categoryName.value = null
}

const timer = ref()
watch(categoryName, (newValue) => {
  AllCategories.value = []
  clearTimeout(timer.value);
  timer.value = setTimeout(async () => {
    const res = await categoriesGetAllAPI(newValue)
    res.data.forEach(category => {
      // 检查当前分类是否已经存在于 AllCategories 中
      const existingCategory = categoryInfo.value.categories.find(c => c.id === category.id);
      if (!existingCategory) {
        // 如果当前分类不存在于 AllCategories 中，则添加到 AllCategories 中
        AllCategories.value.push(category);
      }
    });
  }, 300);
}, { deep: true, immediate: true });

// 添加分类
const addCategory = (newCategory) => {
  categoryInfo.value.categories.push(newCategory)
  dialogVisible.value = false
  AllCategories.value = AllCategories.value.filter(category => category.id !== newCategory.id);
}
</script>

<template>
  <el-form>
    <el-form-item label="关联分类">
      <el-tag
          v-for="(category, index) in categoryInfo.categories"
          :key="index"
          style="margin-right: 5px;"
          closable
          size="large"
          @close="handleDelete(category.id)">
        {{ category.name }}
      </el-tag>
      <el-button type="success" @click="showAllCategories">
        + 添加分类
      </el-button>
    </el-form-item>
    <el-dialog
        width="500px"
        @open="handleOpen"
        draggable
        v-model="dialogVisible">
      <span>分类名:&nbsp;&nbsp;</span>
      <el-input v-model="categoryName" style="width: 240px" placeholder="请输入分类名" />
      <el-scrollbar height="300px">
        <el-button
            type="primary"
            v-for="item in AllCategories"
            style="margin: 10px"
            @click="addCategory(item)"
            :key="item">
          {{ item.name }}
        </el-button>
      </el-scrollbar>
    </el-dialog>
  </el-form>
</template>

<style scoped>

</style>
